package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.WeeklyTemplate;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.GetWeeklyTemplateMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.AllDialogUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 05月 24日
 * Time: 上午11:40
 *
 * @QQ : 1234567890
 * **********************************
 */
public class WeeklyTemplateActivity extends MyBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    @FindViewById(id = R.id.weekly_date_lv)
    private ListView mListView;
    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_ll_layout)
    private LinearLayout mLayoutHelp;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.title_iv_help)
    private ImageView mIvHelp;

    private String mGroupId;
    private int mPosition;
    private int mDeletePosition = -1;

    private AllDialogUtil mDialogUtil;
    private Dialog mWaitDialog;
    private WeeklyMouldAdapter mAdapter;
    private List<WeeklyTemplate> mDatas = new ArrayList<WeeklyTemplate>();

    private static final int EDIT_RESULT = 101;
    private static final int WEEKLY_TEMPLATE_LIST = 10001;
    private static final int WEEKLY_DEFAULT_TEMPLATE = 10002;
    private static final int WEEKLY_DELETE_TEMPLATE = 10003;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WEEKLY_TEMPLATE_LIST:
                    if (msg.arg1 == 0) {
                        mDatas = (List<WeeklyTemplate>) msg.obj;
                        mAdapter.notifyDataSetChanged();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case WEEKLY_DEFAULT_TEMPLATE:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0) {

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case WEEKLY_DELETE_TEMPLATE:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0) {
                        mDatas.remove(mDeletePosition);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.weekly_date_layout);
    }

    @Override
    public void initListener() {
        mTvRight.setOnClickListener(this);
        mLayoutBack.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);
        mLayoutHelp.setOnClickListener(this);
        mIvHelp.setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        mTvTitle.setText("周报模板");
        mTvRight.setText("新建");

        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mAdapter = new WeeklyMouldAdapter();
        mListView.setAdapter(mAdapter);
        getTemplateList();
        mDialogUtil = AllDialogUtil.getInstance(mActivity);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_ll_back:
                finish();
                break;
            case R.id.title_ll_layout:
                Intent help = new Intent(WeeklyTemplateActivity.this, WebViewActivity.class);
                help.putExtra("title", "如何自定义周报模板?");
                help.putExtra("type", 20);
                startActivity(help);
                break;
            case R.id.title_tv_right:
                Intent create = new Intent(mActivity, WeeklyTemplateEditActivity.class);
                create.putExtra("group_id", mGroupId);
                create.setAction("create_template");
                startActivityForResult(create, EDIT_RESULT);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if ("0".equals(mDatas.get(position).getGroup_id())) {
            showShortToast("默认模板不可编辑");
            return;
        }
        Intent edit = new Intent(mActivity, WeeklyTemplateEditActivity.class);
        edit.putExtra("template", mDatas.get(position));
        edit.setAction("edit_template");
        startActivityForResult(edit, EDIT_RESULT);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        WeeklyTemplate template = mDatas.get(position);
        if ("0".equals(template.getGroup_id())) {
            showShortToast("默认模板不可删除");
        } else {
            mDeletePosition = position;
            showDeleteDialog(template.get_id());
        }
        return true;
    }

    public void showDeleteDialog(final String templateId) {
        String okText = this.getString(R.string.label_btn_delete);
        String cancelText = this.getString(R.string.cancel);
        mDialogUtil.titleDeleteMsgStyle(okText, cancelText, "是否要删除此模板");
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                httpReqDlgShow();
                deleteTemplateList(templateId);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            getTemplateList();
        }
    }

    /**
     * 获取模板
     */
    private void getTemplateList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        GetWeeklyTemplateMsg message = new GetWeeklyTemplateMsg(mHandler.obtainMessage(WEEKLY_TEMPLATE_LIST));
        message.mApi = AsynHttpClient.API_EVENT_WEEKLY_TEMPLATE_LIST;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
    }

    /**
     * 删除模板
     */
    private void deleteTemplateList(String templateId) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_TEMPLATE_ID, templateId));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(WEEKLY_DELETE_TEMPLATE));
        message.mApi = AsynHttpClient.API_EVENT_WEEKLY_TEMPLATE_DEL;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
    }

    /**
     * 设置默认模板
     */
    public void seteDfaultTemplate(String templateId) {
        httpReqDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_TEMPLATE_ID, templateId));
        nvps.add(new BasicNameValuePair("is_default", 1 + ""));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(WEEKLY_DEFAULT_TEMPLATE));
        message.mApi = AsynHttpClient.API_EVENT_WEEKLY_TEMPLATE_SET_DEFAULT;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(mActivity).waitDialog();
            mWaitDialog.show();
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    class WeeklyMouldAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mDatas == null ? 0 : mDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return mDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.weekly_mould_select_item_layout, null);
                holder = new ViewHolder();
                holder.mould = (TextView) convertView.findViewById(R.id.weekly_mould_tv);
                holder.layout = (LinearLayout) convertView.findViewById(R.id.weekly_mould_click);
                holder.image = (ImageView) convertView.findViewById(R.id.weekly_mould_iv);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            WeeklyTemplate weeklyTemplate = mDatas.get(position);
            holder.mould.setText(weeklyTemplate.getTemplate_name());
            if (weeklyTemplate.getIs_default() == 1) {
                holder.image.setImageResource(R.drawable.checked);
            } else {
                holder.image.setImageResource(R.drawable.un_check);
            }
            holder.layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mDatas.size() > 1){
                        for (int i = 0; i < mDatas.size(); i++) {
                            mDatas.get(i).setIs_default(0);
                        }
                        mPosition = position;
                        mDatas.get(mPosition).setIs_default(1);
                        notifyDataSetChanged();
                        seteDfaultTemplate(mDatas.get(mPosition).get_id());
                    }
                }
            });

            return convertView;
        }
    }

    class ViewHolder {
        TextView mould;
        ImageView image;
        LinearLayout layout;

    }
}
